package cn.ctodb.mall.web.rest;

import com.codahale.metrics.annotation.Timed;
import cn.ctodb.mall.service.DeliveryOrderService;
import cn.ctodb.mall.web.rest.util.HeaderUtil;
import cn.ctodb.mall.service.dto.DeliveryOrderDTO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing DeliveryOrder.
 */
@RestController
@RequestMapping("/api")
public class DeliveryOrderResource {

    private final Logger log = LoggerFactory.getLogger(DeliveryOrderResource.class);
        
    @Inject
    private DeliveryOrderService deliveryOrderService;

    /**
     * POST  /delivery-orders : Create a new deliveryOrder.
     *
     * @param deliveryOrderDTO the deliveryOrderDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new deliveryOrderDTO, or with status 400 (Bad Request) if the deliveryOrder has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/delivery-orders")
    @Timed
    public ResponseEntity<DeliveryOrderDTO> createDeliveryOrder(@RequestBody DeliveryOrderDTO deliveryOrderDTO) throws URISyntaxException {
        log.debug("REST request to save DeliveryOrder : {}", deliveryOrderDTO);
        if (deliveryOrderDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("deliveryOrder", "idexists", "A new deliveryOrder cannot already have an ID")).body(null);
        }
        DeliveryOrderDTO result = deliveryOrderService.save(deliveryOrderDTO);
        return ResponseEntity.created(new URI("/api/delivery-orders/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("deliveryOrder", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /delivery-orders : Updates an existing deliveryOrder.
     *
     * @param deliveryOrderDTO the deliveryOrderDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated deliveryOrderDTO,
     * or with status 400 (Bad Request) if the deliveryOrderDTO is not valid,
     * or with status 500 (Internal Server Error) if the deliveryOrderDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/delivery-orders")
    @Timed
    public ResponseEntity<DeliveryOrderDTO> updateDeliveryOrder(@RequestBody DeliveryOrderDTO deliveryOrderDTO) throws URISyntaxException {
        log.debug("REST request to update DeliveryOrder : {}", deliveryOrderDTO);
        if (deliveryOrderDTO.getId() == null) {
            return createDeliveryOrder(deliveryOrderDTO);
        }
        DeliveryOrderDTO result = deliveryOrderService.save(deliveryOrderDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("deliveryOrder", deliveryOrderDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /delivery-orders : get all the deliveryOrders.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of deliveryOrders in body
     */
    @GetMapping("/delivery-orders")
    @Timed
    public List<DeliveryOrderDTO> getAllDeliveryOrders() {
        log.debug("REST request to get all DeliveryOrders");
        return deliveryOrderService.findAll();
    }

    /**
     * GET  /delivery-orders/:id : get the "id" deliveryOrder.
     *
     * @param id the id of the deliveryOrderDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the deliveryOrderDTO, or with status 404 (Not Found)
     */
    @GetMapping("/delivery-orders/{id}")
    @Timed
    public ResponseEntity<DeliveryOrderDTO> getDeliveryOrder(@PathVariable Long id) {
        log.debug("REST request to get DeliveryOrder : {}", id);
        DeliveryOrderDTO deliveryOrderDTO = deliveryOrderService.findOne(id);
        return Optional.ofNullable(deliveryOrderDTO)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /delivery-orders/:id : delete the "id" deliveryOrder.
     *
     * @param id the id of the deliveryOrderDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/delivery-orders/{id}")
    @Timed
    public ResponseEntity<Void> deleteDeliveryOrder(@PathVariable Long id) {
        log.debug("REST request to delete DeliveryOrder : {}", id);
        deliveryOrderService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("deliveryOrder", id.toString())).build();
    }

    /**
     * SEARCH  /_search/delivery-orders?query=:query : search for the deliveryOrder corresponding
     * to the query.
     *
     * @param query the query of the deliveryOrder search 
     * @return the result of the search
     */
    @GetMapping("/_search/delivery-orders")
    @Timed
    public List<DeliveryOrderDTO> searchDeliveryOrders(@RequestParam String query) {
        log.debug("REST request to search DeliveryOrders for query {}", query);
        return deliveryOrderService.search(query);
    }


}
